<?php

namespace common\models;

use Yii;

class Category{

    public $table = 'recite_knowledge_category';
    public $primaryKey = 'id';

    public static function test(){
        echo "test";
    }

    /**
     * 得到所有分类数据
     * @return null
     */
    public static function getData(){
        $db = Yii::$app->db;
        $sql = "SELECT id, pid, `name` FROM {{%note_category}} WHERE status=0 ORDER BY id ASC";
        $data = $db->createCommand($sql)->queryAll();
        if(empty($data)){
            return null;
        }else{
            return $data;
        }
    }

    public static function getRow($id, $data=[]){
        $data = (empty($data)) ? self::getData() : $data;
        for($i=0; $i<count($data); $i++){
            if($data[$i]["id"] == $id){
                return $data[$i];
            }
        }
        return [];
    }

    public static function getTree($data = []){
        if(empty($data))$data = self::getData();
        return self::getChildren($data);
    }

    public static function getChildren($datas, $pid = 0){
        $temp = [];
        for($i=0; $i<count($datas); $i++){
            if($datas[$i]["pid"] == $pid){
                $temp_arr =  $datas[$i];
                $children = self::getChildren($datas, $datas[$i]["id"]);
                if(!empty($children)){
                    $temp_arr["children"] = $children;
                }
                $temp[] = $temp_arr;
            }
        }
        return $temp;
    }

    /**
     * 得到导航条数组
     * @param $data
     * @param $id
     * @return array
     */
    public static function getNav($data, $id){
        $ids = self::getParentIdArray($data, [$id]);
        $ids = array_reverse($ids);
        $nav = [];
        for($i=0; $i<count($ids); $i++){
            $nav[$i] = self::getRow($data, $ids[$i]);

            if($i == 0){
                $nav[$i]["link"] = "/manual-cate-".$nav[$i]["id"].".html";
            }else{
                $nav[$i]["link"] = "/manual-cate-2-".$nav[$i]["id"].".html";
            }

        }
        return $nav;
    }

    /**
     * 递归得到当前分类及所有父分类组成的ID数组，比如在显示导航位置的时候会用到
     * @param $data
     * @param $ids
     * @return array
     */
    public static function getParentIdArray($data, $ids){
        if(!is_array($ids) || count($ids) == 0)return [];
        $pid = self::getParentId($data, $ids[count($ids)-1]);
        if($pid == 0){
            return $ids;
        }else{
            $ids[] = $pid;
            return self::getParentIdArray($data, $ids);
        }
    }

    /**
     * 得到一个分类的父类ID
     * @param $data
     * @param $id
     * @return int
     */
    public static function getParentId($data, $id){
        $pid = 0;
        foreach($data as $cat){
            if($cat["id"] == $id){
                $pid = $cat["pid"];
            }
        }
        return $pid;
    }

}
